package com.futvan.z.framework.util;

import jxl.Sheet;
import jxl.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import com.futvan.z.framework.core.z;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文档工具类
 */
public class OfficeUtil {

    public static void main(String[] args) throws Exception{
        Workbook book= Workbook.getWorkbook(new File("d://a.xls"));
        Sheet sheet=book.getSheet(0);
        for(int i=0;i<=sheet.getRows();i++){
            String number = sheet.getCell(0, i).getContents().trim();

            String title123 = sheet.getCell(1, i).getContents().trim();
            if(title123.length()>30){
                title123 = title123.substring(1,30);
            }
            System.out.print(title123);

            String url123 = sheet.getCell(2, i).getContents().trim();
            System.out.print(url123);


            String pt123 = sheet.getCell(3, i).getContents().trim();
            System.out.print(pt123);

            String zz123 = sheet.getCell(5, i).getContents().trim();
            System.out.print(zz123);

            System.out.println();

            HashMap<String, String> keys = new HashMap<>();
            keys.put("title123", title123);
            keys.put("url123", url123);
            keys.put("pt123", pt123);
            keys.put("zz123", zz123);

            ReplaceAndCopyDOCS(new File("d://b.docx"),new File("d://cc/"+number+".doc"),keys);

        }
    }


    private static int ReplaceAndCopyDOCS(File fromfile, File tofile, HashMap<String, String> keys) throws Exception {
        //源文件
        if(z.isNull(fromfile)){
            z.Exception("准备替换的文件未找到："+fromfile.getPath());
        }

        int replace_count = 0;

        FileInputStream fromFileInputStream = new FileInputStream(fromfile.getPath());

        //获取源文件
        XWPFDocument Document = new XWPFDocument(fromFileInputStream);


        //替换页眉
        List<XWPFHeader> xwpfHeaderList = Document.getHeaderList();
        for (XWPFHeader Header : xwpfHeaderList) {
            List<XWPFParagraph> xwpfParagraphList = Header.getParagraphs();
            for (XWPFParagraph paragraph : xwpfParagraphList) {
                String runtext = paragraph.getText();
                if(z.isNotNull(runtext)) {
                    z.Log("解析页眉文档内容："+runtext);
                }

                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    //遍历要替换的信息
                    for (Map.Entry<String, String> entry : keys.entrySet()) {
                        String findText = entry.getKey();
                        String replaceText = entry.getValue();
                        if (runtext.contains(findText)) {
                            //替换段落文本
                            run.setText(runtext.replace(findText,replaceText), 0);
                            z.Log("========> 执行页眉替换：【"+findText+"】 替换成 【"+replaceText+"】");
                            replace_count = replace_count + 1;
                        }
                    }
                }

            }
        }



        //替换页脚
        List<XWPFFooter> XWPFFooterList = Document.getFooterList();
        for (XWPFFooter Footer : XWPFFooterList) {
            List<XWPFParagraph> xwpfParagraphList = Footer.getParagraphs();
            for (XWPFParagraph paragraph : xwpfParagraphList) {
                String runtext = paragraph.getText();
                if(z.isNotNull(runtext)) {
                    z.Log("解析页脚文档内容："+runtext);
                }

                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    //遍历要替换的信息
                    for (Map.Entry<String, String> entry : keys.entrySet()) {
                        String findText = entry.getKey();
                        String replaceText = entry.getValue();
                        if (runtext.contains(findText)) {
                            //替换段落文本
                            run.setText(runtext.replace(findText,replaceText), 0);
                            z.Log("========> 执行页脚替换：【"+findText+"】 替换成 【"+replaceText+"】");
                            replace_count = replace_count + 1;
                        }
                    }
                }

            }
        }


        //替换段落只的文字
        List<XWPFParagraph> paragraphs = Document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            //判断此段落时候需要进行替换
            String text = paragraph.getText();
            List<XWPFRun> runs = paragraph.getRuns();
            //遍历所有段落
            for (XWPFRun run : runs) {
                //获取段落文本
                String runtext = run.getText(0);
                if(z.isNotNull(runtext)) {
                    z.Log("解析文档内容："+runtext);
                }

                if(z.isNotNull(runtext)){
                    //遍历要替换的信息
                    for (Map.Entry<String, String> entry : keys.entrySet()) {
                        String findText = entry.getKey();
                        String replaceText = entry.getValue();
                        if (runtext.contains(findText)) {
                            //替换段落文本
                            run.setText(runtext.replace(findText,replaceText), 0);
                            z.Log("========> 执行替换：【"+findText+"】 替换成 【"+replaceText+"】");
                            replace_count = replace_count + 1;
                        }
                    }
                }
            }
        }

        //替换表格中的文字
        List<XWPFTable> tables = Document.getTables();
        for (XWPFTable table : tables) {
            List<XWPFTableRow> rows = table.getRows();
            for (XWPFTableRow row : rows) {
                //得到表格每一行的所有表格
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        for (XWPFRun r : p.getRuns()) {
                            String runtext = r.getText(0);
                            //遍历要替换的信息
                            for (Map.Entry<String, String> entry : keys.entrySet()) {
                                String findText = entry.getKey();
                                String replaceText = entry.getValue();
                                if (runtext != null && runtext.contains(findText)) {
                                    //替换段落文本
                                    r.setText(runtext.replace(findText,replaceText),0);
                                    replace_count = replace_count + 1;
                                }
                            }
                        }
                    }
                }
            }
        }

        //保存新的文件
        File toDir = new File(tofile.getParent());
        if(!toDir.exists()){
            //如果输出目录没有，自动创建
            toDir.mkdirs();
        }
        try (FileOutputStream out = new FileOutputStream(tofile)) {
            Document.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Document.close();
        fromFileInputStream.close();

        return replace_count;
    }


}
